package com.ssttevee.taskmanagerapp.tasks;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;

import net.robotmedia.billing.model.Transaction;

import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.Log;

public class ServerCommunicator {
	private Context context;
	
	public ServerCommunicator(Context context) {
		this.context = context;
	}
	
	public boolean storeUpgradedDevice(Transaction t) {

		SharedPreferences myPrefs = context.getSharedPreferences("mclprefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
		Hashtable<String, String> h = new Hashtable<String, String>();
		h.put("udid", ((TelephonyManager) this.context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
		h.put("payload", t.developerPayload);
		h.put("time", t.purchaseTime + "");
		h.put("product", t.productId);
		h.put("orderid", t.orderId);
		h.put("country", this.context.getResources().getConfiguration().locale.getDisplayCountry());
		
		try {
			String result = POST("http://droid.ssttevee.com/collect/purchase_data.php", h);
			Log.d("PostData", result);
			
			if(result == "OK") {
		        prefsEditor.putString("SERVER_NOTIFIED", "true");
				prefsEditor.commit();
				return true;
			} else {
		        prefsEditor.putString("SERVER_NOTIFIED", "false");
				prefsEditor.commit();
				return false;
			}
		} catch (Exception e) {
	        prefsEditor.putString("SERVER_NOTIFIED", "false");
			prefsEditor.commit();
			Log.e("PostData", e.getMessage());
			return false;
		} finally {
		}
		
	}
	
	public boolean checkLicence(String productId) {
		
		Hashtable<String, String> h = new Hashtable<String, String>();
		h.put("udid", ((TelephonyManager) this.context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
		h.put("productId", productId);
		
		try {
			String result = POST("http://droid.ssttevee.com/distrib/checkDeviceLicence.php", h);
			Log.d("PostData", result);
			
			return Boolean.parseBoolean(result.trim());
		} catch (Exception e) {
			Log.e("PostData", e.getMessage());
			return false;
		}
	}
	
	public boolean postAddedServer(Task t) {
		
		Hashtable<String, String> h = new Hashtable<String, String>();
		h.put("udid", ((TelephonyManager) this.context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
		h.put("sname", t.getName());
		h.put("shost", t.getHost());
		h.put("country", this.context.getResources().getConfiguration().locale.getDisplayCountry());
		
		try {
			String result = POST("http://droid.ssttevee.com/collect/servers.php", h);
			Log.d("PostData", result);
			
			if(result == "OK") {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			Log.e("PostData", e.getMessage());
			return false;
		}
	}
	
	public static String POST(String targetURL, Hashtable<String, String> contentHash) throws Exception {	 
		URL url;
		URLConnection conn;
		DataOutputStream out;
		DataInputStream in;
		url = new URL (targetURL); 
		conn = url.openConnection();
		conn.setDoInput (true); 
		conn.setDoOutput (true); 
		conn.setUseCaches (false);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		
		out = new DataOutputStream (conn.getOutputStream ());
		String content = "";
		
		Enumeration<String> e = contentHash.keys();
		boolean first = true;
		while(e.hasMoreElements()) 
		{
			Object key = e.nextElement(); 
			Object value = contentHash.get(key); 
			
			if(!first) {
				content += "&";
			}
			
			content += (String)key + "=" + URLEncoder.encode((String)value);
			
			first = false;
		}
		
		out.writeBytes (content); 
		out.flush (); 
		out.close (); 
		
		in = new DataInputStream (conn.getInputStream ()); 

		String returnString = "";
		String str;
		while (null != (str = in.readLine())) {
			returnString += str + "\n";
		}
		
		in.close ();
		
		return returnString;
	} 

}
